package com.zoe.app.listener;

import cn.hutool.core.util.IdUtil;
import com.zoe.app.entity.SysUser;
import com.zoe.app.event.ZoeTransactionEvent;
import com.zoe.app.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @author zbg
 * @date 2024/02/22
 * @description
 */
@Slf4j
@Component
public class ZoeTransactionListener {
    @Autowired
    SysUserService sysUserService;


    // @Async
    // TransactionalEventListener:报错不会回滚,并且发送该事务的方法必须要被事务所管理,否则无法触发
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, classes = ZoeTransactionEvent.class)
    // @EventListener(classes = {ZoeTransactionEvent.class}) // 报错会回滚
    public void onApplicationEvent(ZoeTransactionEvent zoeTransactionEvent) {
        log.info("事务提交");
        System.out.println(zoeTransactionEvent);
        SysUser sysUser = zoeTransactionEvent.getSysUser();
        sysUser.setName(sysUser.getName() + IdUtil.fastSimpleUUID());
        sysUserService.save(sysUser);
    }
}
